import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { getSessionStore } from '../utils/helpers';
class Http {
    // 基础路径
    public baseURL: string = 'http://localhost:7001'
    // 超时时间
    private timeout: number = 5000
    constructor() {
    }
    mergeOptions(options: AxiosRequestConfig) {
        return {
            baseURL: this.baseURL,
            timeout: this.timeout,
            ...options
        }
    }
    createInterceptor(instance: AxiosInstance) {
        instance.interceptors.request.use(options => {
            // 后端允许cookie的话，要在这里添加一个字段
            options.withCredentials = true;

            // 添加Authoriation字段 即请求头加token
            let token = getSessionStore('token');
            if (token) {
                token = 'Bears ' + token;
                options.headers.Authorization = token;
            }
            return options;
        }, err => {
            return Promise.reject(err);
        });
        // instance.interceptors.response.use(function (response){
        //     return Promise.resolve(response.data);
        // }, err => {
        //     Promise.reject(err);
        // });
    }
    request(options: AxiosRequestConfig) {
        // 创建单独的axios实例，好处是单独为每个请求创建拦截器
        const instance = axios.create();
        // 设置拦截器
        this.createInterceptor(instance);
        // 合并请求对象
        options = this.mergeOptions(options);
        return instance(options);
    }
    get(url: string, options = {}) {
        return this.request({
            url,
            method: 'get',
            ...options
        })
    }
    post(url: string, options = {}) {
        return this.request({
            url,
            method: 'post',
            ...options
        })
    }
}
const http = new Http();
export const baseURL = http.baseURL;
export default http;

